#!/usr/bin/env bash
# environment variables
PROJECT_DIR=$(dirname "$(dirname "$(readlink -f "$0")")")
XDISPLAY=${XDISPLAY:-:1}
SCREEN_SIZE=${SCREEN_SIZE:-960x540}
LOG_PATH=${PROJECT_DIR}/docs/screenshots/take_all.log
GEOMETRY=${GEOMETRY:-240x135}
DELAY=${DELAY:-1x1}
BORDER_FOCUS=${BORDER_FOCUS:-#ff0000}
BORDER_NORMAL=${BORDER_NORMAL:-#000000}
BORDER_WIDTH=${BORDER_WIDTH:-8}
MARGIN=${MARGIN:-10}
if [[ -z "${PYTHON}" ]]; then
  if [[ -f "${PROJECT_DIR}/venv/bin/python3" ]]; then
    PYTHON="${PROJECT_DIR}/venv/bin/python3"
  else
    PYTHON=python3
  fi
fi

# run command in nested X window with specific env vars
nested() {
  env \
    DISPLAY=${XDISPLAY} \
    PYTHON="${PYTHON}" \
    LOG_PATH="${LOG_PATH}" \
    GEOMETRY="${GEOMETRY}" \
    DELAY="${DELAY}" \
    BORDER_FOCUS="${BORDER_FOCUS}" \
    BORDER_NORMAL="${BORDER_NORMAL}" \
    BORDER_WIDTH="${BORDER_WIDTH}" \
    MARGIN="${MARGIN}" \
    "$@"
}

rm "${LOG_PATH}" &>/dev/null
touch "${LOG_PATH}"
tail -f "${LOG_PATH}" &
TAIL_PID=$!

Xephyr +extension RANDR -screen ${SCREEN_SIZE} ${XDISPLAY} -ac &>/dev/null &
XEPHYR_PID=$!

(
  sleep 1
  nested "${PYTHON}" "${PROJECT_DIR}/bin/qtile" -l CRITICAL -c "${PROJECT_DIR}/docs/screenshots/config.py" &
  QTILE_PID=$!

  case $1 in
    -i|--interactive)
      nested xterm
    ;;
    *)
      sleep 1
      nested xterm -e "${PYTHON}" "${PROJECT_DIR}/docs/screenshots/take_all.py" "$@"
      kill $TAIL_PID
      nested xterm -e qtile cmd-obj -o cmd -f shutdown
    ;;
  esac

  wait $QTILE_PID
  kill $XEPHYR_PID
)
